import React, { Component } from 'react';
import { connect } from 'react-redux';
import AdvancedQuery from '../AdvancedQuery';
import dataCenter from '../../dataCenter';
import {
	Input,
	Collapse,
	Button,
	Row,
	Col,
	Icon,
	Form,
	Select,
	InputNumber,
	Card
} from 'antd';

import * as d3 from 'd3';

const FormItem = Form.Item;
const Option = Select.Option;
const OptGroup = Select.OptGroup;

import {
	updateData,
	getAllNodesCount,
	getAllRelationshipsCount,
	advancedQueryNodes,
	getAllRelationTypes,
} from '../../action';


const Panel = Collapse.Panel;

class NodeSearch extends Component {
	componentDidMount() {
		this.props.dispatch(getAllNodesCount());
		this.props.dispatch(getAllRelationshipsCount());
		dataCenter.getLabels().then(labels => {
			this.setState({
				labels
			})
		});
		dataCenter.getPropertyKeys().then(propertyKeys => {
			this.setState({
				propertyKeys
			})
		})
		dataCenter.getAllRelationTypes().then(relationTypes => {
			this.setState({
				relationTypes
			})
		})
	}
	state = {
		directionComType: 'out',
		labels: [],
		propertyKeys: [],
		relationTypes: [],
		minLength: null,
		maxLength: null
	}
	search = () => {
		this.props.setSearchType('node');
		if (this.refs.searchValue.refs.input.value) 
		this.props.dispatch(updateData(this.refs.searchValue.refs.input.value));
	}

	getAllNodesCount = () => {
		this.props.setSearchType('');
		this.props.dispatch(getAllNodesCount());
	}

	searchDetailNode = (searchData) => {
		const staticParams = {q: searchData.q, labels: searchData.labels};
		const dealedSearchData = _.cloneDeep(searchData);
		delete dealedSearchData.q;
		delete dealedSearchData.labels;
		const props = Object.keys(dealedSearchData).reduce((pre, key, index) => {
			if (dealedSearchData[key]) {
				return [...pre, [key, dealedSearchData[key]]]
			} else {
				return pre;
			}
		}, []);
		let dealedParams = {...staticParams, props, graph: true, limit: 20};
		const finalParams = props.length ? dealedParams : {...staticParams, graph: true, limit: 20};
		if (finalParams.q) {
			this.props.setSearchType('node');
			this.props.dispatch(advancedQueryNodes(finalParams));
		}
	}

	render() {
		const { directionComType, labels, propertyKeys, relationTypes } = this.state;
		return (
			<Collapse accordion defaultActiveKey={["active"]}>
		    <Panel header="节点模糊查询" key="1">
		      <Input ref="searchValue"/>
		      <Row style={{marginTop: 7, textAlign: 'right'}}>
		      	<Button onClick={this.search}>查询</Button>
		      </Row>
		    </Panel>
		    <Panel header="节点高级查询" key="2">
		    	<AdvancedQuery searchDetailNode={this.searchDetailNode} labels={labels} propertyKeys={propertyKeys}/>
		    </Panel>
			</Collapse>
		)
	}
}

function mapState2Props(state) {
	let { graphData: { nodesCount, relationshipsCount } } = state;
	return { nodesCount, relationshipsCount };
}

NodeSearch = connect(mapState2Props)(NodeSearch);

export default NodeSearch;